#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API服务器 - 提供实时评估功能
"""

import json
import os
import sys
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import threading
import time
from datetime import datetime
import sqlite3
import logging
import traceback

# 修复Windows控制台中文显示乱码问题
if sys.platform == 'win32':
    import io
    # 设置标准输出编码为UTF-8
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
    # 设置控制台代码页为UTF-8
    try:
        os.system('chcp 65001 >nul 2>&1')
    except:
        pass

# 配置logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.FileHandler('logs/api_server.log', encoding='utf-8')
    ]
)

logger = logging.getLogger(__name__)

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from monitor import N8nMonitor
from config import DB_CONFIG, DEEPSEEK_API_KEY

class APIRequestHandler(BaseHTTPRequestHandler):
    """API请求处理器"""
    
    def __init__(self, *args, **kwargs):
        self.monitor = None
        super().__init__(*args, **kwargs)
    
    def do_GET(self):
        """处理GET请求"""
        try:
            parsed_path = urlparse(self.path)
            path = parsed_path.path
            query_params = parse_qs(parsed_path.query)
            
            if path == '/api/salary-analysis':
                self.handle_salary_analysis(query_params)
            elif path == '/api/candidate-messages':
                self.handle_candidate_messages(query_params)
            elif path == '/api/evaluate-message':
                self.handle_evaluate_message(query_params)
            elif path == '/api/health':
                self.handle_health()
            elif path == '/api/evaluation-statistics':
                self.handle_evaluation_statistics()
            else:
                self.send_error(404, "Not Found")
                
        except Exception as e:
            self.send_error(500, f"Internal Server Error: {str(e)}")
    
    def do_POST(self):
        """处理POST请求"""
        try:
            parsed_path = urlparse(self.path)
            path = parsed_path.path
            
            if path == '/api/evaluate-message':
                self.handle_evaluate_message_post()
            elif path == '/api/batch-evaluate':
                self.handle_batch_evaluate_post()
            elif path == '/api/export-evaluations':
                self.handle_export_evaluations_post()
            else:
                self.send_error(404, "Not Found")
                
        except Exception as e:
            self.send_error(500, f"Internal Server Error: {str(e)}")
    
    def handle_salary_analysis(self, query_params):
        """处理薪资分析请求"""
        try:
            # 获取参数
            days = int(query_params.get('days', [7])[0])
            
            # 确保监控器已初始化
            if not self.monitor:
                self.monitor = N8nMonitor(DB_CONFIG, DEEPSEEK_API_KEY)
                if not self.monitor.connect_db():
                    self.send_error(500, "Database connection failed")
                    return
            
            # 执行AI薪资分析
            result = self.monitor.analyze_salary_with_ai(days)
            
            # 返回结果
            self.send_response(200)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            response_data = {
                'success': True,
                'data': result,
                'timestamp': datetime.now().isoformat()
            }
            
            self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode('utf-8'))
            
        except Exception as e:
            self.send_error(500, f"Salary analysis failed: {str(e)}")
    
    def handle_candidate_messages(self, query_params):
        """处理候选人消息请求"""
        try:
            candidate_id = query_params.get('candidate_id', [None])[0]
            if not candidate_id:
                self.send_error(400, "Missing candidate_id parameter")
                return
            
            # 确保监控器已初始化
            if not self.monitor:
                self.monitor = N8nMonitor(DB_CONFIG, DEEPSEEK_API_KEY)
                if not self.monitor.connect_db():
                    self.send_error(500, "Database connection failed")
                    return
            
            # 获取候选人聊天记录
            result = self.monitor.get_user_chat_records(int(candidate_id))
            
            # 返回结果
            self.send_response(200)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            response_data = {
                'success': True,
                'data': result,
                'timestamp': datetime.now().isoformat()
            }
            
            self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode('utf-8'))
            
        except Exception as e:
            self.send_error(500, f"Failed to get candidate messages: {str(e)}")
    
    def handle_evaluate_message(self, query_params):
        """处理单条消息评估请求"""
        try:
            message = query_params.get('message', [None])[0]
            if not message:
                self.send_error(400, "Missing message parameter")
                return
            
            # 确保监控器已初始化
            if not self.monitor:
                self.monitor = N8nMonitor(DB_CONFIG, DEEPSEEK_API_KEY)
            
            if not self.monitor.ai_enabled:
                self.send_error(503, "AI evaluation not available")
                return
            
            # 评估消息
            result = self.monitor.salary_analyzer.evaluator.evaluate_salary_info(message)
            
            # 返回结果
            self.send_response(200)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            response_data = {
                'success': True,
                'data': result,
                'timestamp': datetime.now().isoformat()
            }
            
            self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode('utf-8'))
            
        except Exception as e:
            self.send_error(500, f"Message evaluation failed: {str(e)}")
    
    def handle_evaluate_message_post(self):
        """处理POST消息评估请求"""
        try:
            # 读取请求体
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode('utf-8'))
            
            message = data.get('message')
            if not message:
                self.send_error(400, "Missing message in request body")
                return
            
            # 确保监控器已初始化
            if not self.monitor:
                self.monitor = N8nMonitor(DB_CONFIG, DEEPSEEK_API_KEY)
            
            if not self.monitor.ai_enabled:
                self.send_error(503, "AI evaluation not available")
                return
            
            # 评估消息
            result = self.monitor.salary_analyzer.evaluator.evaluate_salary_info(message)
            
            # 返回结果
            self.send_response(200)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            response_data = {
                'success': True,
                'data': result,
                'timestamp': datetime.now().isoformat()
            }
            
            self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode('utf-8'))
            
        except Exception as e:
            self.send_error(500, f"Message evaluation failed: {str(e)}")
    
    def handle_health(self):
        """处理健康检查请求"""
        self.send_response(200)
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        
        response_data = {
            'status': 'healthy',
            'timestamp': datetime.now().isoformat(),
            'ai_enabled': self.monitor.ai_enabled if self.monitor else False
        }
        
        self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode('utf-8'))
    
    def handle_batch_evaluate_post(self):
        """处理批量评估POST请求"""
        try:
            # 读取请求体
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode('utf-8'))
            
            limit = data.get('limit', 50)
            
            # 执行批量评估
            self.perform_batch_evaluation(limit)
            
        except Exception as e:
            self.send_error(500, f"Batch evaluation failed: {str(e)}")
    
    def perform_batch_evaluation(self, limit):
        """执行批量评估"""
        try:
            print("\n========== 开始批量评估 ==========")
            
            # 确保监控器已初始化
            if not self.monitor:
                print("[DEBUG] 初始化monitor...")
                self.monitor = N8nMonitor(DB_CONFIG, DEEPSEEK_API_KEY)
                if not self.monitor.connect_db():
                    self.send_error(500, "Database connection failed")
                    return
            
            if not self.monitor.ai_enabled:
                self.send_error(503, "AI evaluation not available")
                return
            
            print(f"[DEBUG] 评估消息条数限制: {limit}")
            
            # 获取候选人列表
            query = """
            SELECT DISTINCT c.id, c.name, c.boss_uid, c.updated_at
            FROM candidates c
            WHERE c.updated_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
            ORDER BY c.updated_at DESC
            """
            self.monitor.cursor.execute(query)
            candidates = self.monitor.cursor.fetchall()
            
            print(f"[DEBUG] 找到候选人: {len(candidates)}")
            
            # 收集所有消息
            all_messages = []
            
            for idx, candidate in enumerate(candidates):
                candidate_id = candidate['id']
                candidate_name = candidate['name']
                
                # 获取该候选人的消息（只获取AI发送的消息）
                msg_query = """
                SELECT id, content, created_at
                FROM messages
                WHERE candidate_id = %s AND sender = '我'
                ORDER BY created_at DESC
                LIMIT %s
                """
                self.monitor.cursor.execute(msg_query, (candidate_id, limit))
                messages = self.monitor.cursor.fetchall()
                
                print(f"[DEBUG] 候选人 {candidate_name}: {len(messages)} 条AI消息")
                
                for msg in messages:
                    all_messages.append({
                        'id': msg['id'],
                        'content': msg['content'],
                        'candidate_id': candidate_id,
                        'candidate_name': candidate_name,
                        'created_at': str(msg['created_at'])
                    })
            
            print(f"[DEBUG] 收集到的总AI消息数: {len(all_messages)}")
            
            # 如果有limit限制，只评估前N条
            original_count = len(all_messages)
            if limit > 0:
                all_messages = sorted(all_messages, key=lambda x: x['created_at'], reverse=True)[:limit]
                print(f"[DEBUG] 应用限制后消息数: {len(all_messages)} (原始: {original_count})")
            
            # 批量评估
            evaluations = []
            total_messages_to_evaluate = len(all_messages)
            evaluated_count = 0
            failed_count = 0
            pending_count = 0
            
            print(f"[DEBUG] 开始评估 {total_messages_to_evaluate} 条消息...")
            
            for i, msg in enumerate(all_messages):
                try:
                    result = self.monitor.salary_analyzer.evaluator.evaluate_salary_info(msg['content'])
                    evaluations.append({
                        'message_id': msg['id'],
                        'candidate_id': msg['candidate_id'],
                        'candidate_name': msg['candidate_name'],
                        'content': msg['content'],
                        'created_at': msg['created_at'],
                        'evaluation': result,
                        'status': 'evaluated' if result.get('success') else 'failed'
                    })
                    if result.get('success'):
                        evaluated_count += 1
                    else:
                        failed_count += 1
                    
                    if (i + 1) % 10 == 0:
                        print(f"[DEBUG] 已评估 {i + 1}/{total_messages_to_evaluate} 条")
                except Exception as e:
                    print(f"[DEBUG] 评估消息 {msg['id']} 时出错: {str(e)}")
                    evaluations.append({
                        'message_id': msg['id'],
                        'candidate_id': msg['candidate_id'],
                        'candidate_name': msg['candidate_name'],
                        'content': msg['content'],
                        'created_at': msg['created_at'],
                        'evaluation': {
                            'success': False,
                            'error': str(e),
                            'score': 0,
                            'is_salary_related': False
                        },
                        'status': 'failed'
                    })
                    failed_count += 1
            
            # 计算待评估数（如果有更多消息未评估）
            if limit > 0 and original_count > limit:
                pending_count = original_count - limit
            
            # 统计结果
            salary_messages = [e for e in evaluations if e.get('evaluation', {}).get('is_salary_related', False) and e.get('status') == 'evaluated']
            photo_messages = [e for e in evaluations if e.get('evaluation', {}).get('is_photo_request', False) and e.get('status') == 'evaluated']
            non_salary_messages = [e for e in evaluations if not e.get('evaluation', {}).get('is_salary_related', False) and e.get('status') == 'evaluated']
            
            response_data = {
                'success': True,
                'total_candidates': len(candidates),
                'total_messages': len(evaluations),  # 实际评估的消息数
                'total_ai_messages': len(all_messages),  # 评估到的AI消息数
                'evaluated_count': evaluated_count,  # 成功评估数
                'failed_count': failed_count,  # 评估失败数
                'pending_count': pending_count,  # 未评估消息数
                'salary_messages_count': len(salary_messages),
                'photo_messages_count': len(photo_messages),
                'non_salary_messages_count': len(non_salary_messages),
                'salary_messages': salary_messages[:100],  # 限制返回数量
                'non_salary_messages': non_salary_messages[:100],  # 限制返回数量
                'all_evaluations': evaluations,  # 包含所有评估数据，用于导出
                'timestamp': datetime.now().isoformat()
            }
            
            # DEBUG: 打印返回的数据统计
            print("\n========== API响应数据 ==========")
            print(f"总候选人数: {response_data['total_candidates']}")
            print(f"总消息数(已评估): {response_data['total_messages']}")
            print(f"总AI消息数: {response_data['total_ai_messages']}")
            print(f"已评估数: {response_data['evaluated_count']}")
            print(f"失败数: {response_data['failed_count']}")
            print(f"待评估数: {response_data['pending_count']}")
            print(f"薪资相关消息数: {response_data['salary_messages_count']}")
            print(f"非薪资消息数: {response_data['non_salary_messages_count']}")
            print(f"评估数据总数: {len(response_data['all_evaluations'])}")
            print("==================================\n")
            
            # 保存统计结果到数据库
            logger.info("保存评估统计结果...")
            try:
                self.save_evaluation_statistics(response_data)
                logger.info("评估统计结果保存成功")
            except Exception as e:
                logger.error(f"保存评估统计结果失败: {str(e)}")
                logger.error(f"错误堆栈: {traceback.format_exc()}")
            
            # 返回结果
            self.send_response(200)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode('utf-8'))
            
        except Exception as e:
            self.send_error(500, f"Batch evaluation failed: {str(e)}")
    
    def log_message(self, format, *args):
        """重写日志方法，减少输出"""
        pass
    
    def handle_export_evaluations_post(self):
        """处理导出评估结果POST请求"""
        try:
            logger.info("========== 开始处理导出请求 ==========")
            print("\n" + "="*60)
            print("📤 收到导出请求")
            print("="*60)
            
            # 读取请求体
            content_length = int(self.headers['Content-Length'])
            logger.debug(f"请求体长度: {content_length} bytes")
            
            post_data = self.rfile.read(content_length)
            logger.debug(f"已读取请求体数据")
            
            data = json.loads(post_data.decode('utf-8'))
            logger.debug(f"解析后的数据键: {list(data.keys())}")
            
            evaluations = data.get('evaluations', [])
            logger.info(f"接收到评估数据条数: {len(evaluations)}")
            print(f"📊 接收到的评估数据条数: {len(evaluations)}")
            
            if len(evaluations) == 0:
                logger.warning("没有可导出的评估数据")
                print("⚠️  没有可导出的评估数据")
                self.send_error(400, "No evaluations to export")
                print("="*60 + "\n")
                return
            
            # 显示评估数据样本
            if len(evaluations) > 0:
                print(f"📝 第一条评估数据预览:")
                first_eval = evaluations[0]
                print(f"  - message_id: {first_eval.get('message_id')}")
                print(f"  - candidate_id: {first_eval.get('candidate_id')}")
                print(f"  - candidate_name: {first_eval.get('candidate_name')}")
                print(f"  - 是否薪资相关: {first_eval.get('evaluation', {}).get('is_salary_related', 'N/A')}")
            
            # 导出到SQLite数据库
            logger.info("开始导出到SQLite数据库...")
            print("💾 开始导出到SQLite数据库...")
            export_result = self.export_to_sqlite(evaluations)
            logger.info(f"导出完成，共导出 {export_result['count']} 条记录")
            print(f"✅ 导出完成！共导出 {export_result['count']} 条记录")
            print(f"📁 数据库路径: {export_result['db_path']}")
            
            # 返回结果
            self.send_response(200)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            response_data = {
                'success': True,
                'exported_count': export_result['count'],
                'db_path': export_result['db_path'],
                'timestamp': datetime.now().isoformat()
            }
            
            logger.info("========== 导出请求处理成功 ==========")
            print("="*60 + "\n")
            self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode('utf-8'))
            
        except Exception as e:
            logger.error(f"导出失败: {str(e)}")
            logger.error(f"错误堆栈: {traceback.format_exc()}")
            print(f"❌ 导出失败: {str(e)}")
            print("="*60 + "\n")
            self.send_error(500, f"Export failed: {str(e)}")
    
    def export_to_sqlite(self, evaluations):
        """导出评估结果到SQLite数据库"""
        import os
        
        try:
            logger.info(f"开始导出 {len(evaluations)} 条评估数据到SQLite...")
            
            # 创建数据库文件路径（添加时间戳）
            db_dir = 'exports'
            if not os.path.exists(db_dir):
                logger.debug(f"创建exports目录: {db_dir}")
                os.makedirs(db_dir)
            
            # 生成带时间戳的文件名
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            db_filename = f'salary_evaluations_{timestamp}.db'
            db_path = os.path.join(db_dir, db_filename)
            logger.debug(f"数据库路径: {db_path}")
            print(f"📝 数据库文件: {db_filename}")
            
            # 连接SQLite数据库
            logger.debug("连接到SQLite数据库...")
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            
            # 创建表
            logger.debug("创建数据库表...")
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS salary_evaluations (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    message_id INTEGER,
                    candidate_id INTEGER,
                    candidate_name TEXT,
                    content TEXT,
                    created_at TEXT,
                    is_salary_related INTEGER,
                    score INTEGER,
                    reason TEXT,
                    detected_keywords TEXT,
                    evaluation_timestamp TEXT
                )
            ''')
            
            # 创建索引
            logger.debug("创建数据库索引...")
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_candidate_id ON salary_evaluations(candidate_id)')
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_message_id ON salary_evaluations(message_id)')
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_salary_related ON salary_evaluations(is_salary_related)')
            
            # 插入数据
            count = 0
            print(f"📥 开始插入 {len(evaluations)} 条数据...")
            
            for idx, eval_data in enumerate(evaluations):
                try:
                    logger.debug(f"处理第 {idx + 1} 条评估数据...")
                    
                    # 获取evaluation字段
                    evaluation = eval_data.get('evaluation', {})
                    logger.debug(f"评估数据键: {list(eval_data.keys())}")
                    logger.debug(f"evaluation键: {list(evaluation.keys()) if evaluation else 'None'}")
                    
                    # 准备插入数据
                    insert_data = (
                        eval_data.get('message_id'),
                        eval_data.get('candidate_id'),
                        eval_data.get('candidate_name'),
                        eval_data.get('content'),
                        eval_data.get('created_at'),
                        1 if evaluation.get('is_salary_related') else 0,
                        evaluation.get('score', 0),
                        evaluation.get('reason', ''),
                        json.dumps(evaluation.get('detected_keywords', []), ensure_ascii=False),
                        datetime.now().isoformat()
                    )
                    
                    logger.debug(f"插入数据: message_id={insert_data[0]}, candidate_id={insert_data[1]}, is_salary_related={insert_data[5]}")
                    
                    cursor.execute('''
                        INSERT INTO salary_evaluations 
                        (message_id, candidate_id, candidate_name, content, created_at, 
                         is_salary_related, score, reason, detected_keywords, evaluation_timestamp)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ''', insert_data)
                    
                    count += 1
                    
                    # 每10条显示一次进度
                    if (idx + 1) % 10 == 0:
                        logger.debug(f"已插入 {idx + 1}/{len(evaluations)} 条数据")
                        print(f"  ... 已插入 {idx + 1}/{len(evaluations)} 条数据")
                        
                except Exception as e:
                    logger.error(f"插入第 {idx + 1} 条数据时出错: {str(e)}")
                    logger.error(f"数据内容: {json.dumps(eval_data, ensure_ascii=False)}")
                    logger.error(f"错误堆栈: {traceback.format_exc()}")
                    raise
            
            logger.debug("提交事务...")
            conn.commit()
            conn.close()
            
            logger.info(f"成功导出 {count} 条数据到 {os.path.abspath(db_path)}")
            
            return {
                'count': count,
                'db_path': os.path.abspath(db_path)
            }
            
        except Exception as e:
            logger.error(f"导出到SQLite失败: {str(e)}")
            logger.error(f"错误堆栈: {traceback.format_exc()}")
            raise
    
    def save_evaluation_statistics(self, statistics):
        """保存评估统计结果到SQLite数据库"""
        try:
            logger.info("开始保存评估统计结果...")
            
            # 创建数据库目录
            db_dir = 'data'
            if not os.path.exists(db_dir):
                os.makedirs(db_dir)
            
            db_path = os.path.join(db_dir, 'evaluation_statistics.db')
            
            # 连接SQLite数据库
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            
            # 创建表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS evaluation_statistics (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    timestamp TEXT,
                    total_candidates INTEGER,
                    total_messages INTEGER,
                    total_ai_messages INTEGER,
                    evaluated_count INTEGER,
                    failed_count INTEGER,
                    pending_count INTEGER,
                    salary_messages_count INTEGER,
                    non_salary_messages_count INTEGER,
                    photo_messages_count INTEGER,
                    statistics_data TEXT
                )
            ''')
            
            # 插入统计数据
            insert_data = (
                statistics.get('timestamp', datetime.now().isoformat()),
                statistics.get('total_candidates', 0),
                statistics.get('total_messages', 0),
                statistics.get('total_ai_messages', 0),
                statistics.get('evaluated_count', 0),
                statistics.get('failed_count', 0),
                statistics.get('pending_count', 0),
                statistics.get('salary_messages_count', 0),
                statistics.get('non_salary_messages_count', 0),
                statistics.get('photo_messages_count', 0),
                json.dumps(statistics, ensure_ascii=False)
            )
            
            cursor.execute('''
                INSERT INTO evaluation_statistics 
                (timestamp, total_candidates, total_messages, total_ai_messages, 
                 evaluated_count, failed_count, pending_count, 
                 salary_messages_count, non_salary_messages_count, photo_messages_count,
                 statistics_data)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', insert_data)
            
            conn.commit()
            conn.close()
            
            logger.info(f"评估统计结果已保存到: {os.path.abspath(db_path)}")
            
        except Exception as e:
            logger.error(f"保存评估统计结果失败: {str(e)}")
            logger.error(f"错误堆栈: {traceback.format_exc()}")
            raise
    
    def handle_evaluation_statistics(self):
        """处理获取评估统计请求"""
        try:
            logger.info("收到获取评估统计请求")
            
            # 从数据库获取最新的统计数据
            db_dir = 'data'
            db_path = os.path.join(db_dir, 'evaluation_statistics.db')
            
            if not os.path.exists(db_path):
                # 数据库不存在，返回空数据
                response_data = {
                    'success': True,
                    'has_data': False,
                    'message': '暂无评估统计',
                    'timestamp': datetime.now().isoformat()
                }
            else:
                # 连接数据库并获取最新统计数据
                conn = sqlite3.connect(db_path)
                cursor = conn.cursor()
                
                cursor.execute('''
                    SELECT * FROM evaluation_statistics 
                    ORDER BY timestamp DESC 
                    LIMIT 1
                ''')
                
                row = cursor.fetchone()
                conn.close()
                
                if row:
                    # 返回详细统计数据
                    response_data = {
                        'success': True,
                        'has_data': True,
                        'timestamp': row[1],
                        'total_candidates': row[2],
                        'total_messages': row[3],
                        'total_ai_messages': row[4],
                        'evaluated_count': row[5],
                        'failed_count': row[6],
                        'pending_count': row[7],
                        'salary_messages_count': row[8],
                        'non_salary_messages_count': row[9],
                        'photo_messages_count': row[10],
                        'data': json.loads(row[11]) if row[11] else {}
                    }
                else:
                    # 数据库存在但没有数据
                    response_data = {
                        'success': True,
                        'has_data': False,
                        'message': '暂无评估统计',
                        'timestamp': datetime.now().isoformat()
                    }
            
            logger.info("返回评估统计结果")
            
            # 返回结果
            self.send_response(200)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode('utf-8'))
            
        except Exception as e:
            logger.error(f"获取评估统计失败: {str(e)}")
            logger.error(f"错误堆栈: {traceback.format_exc()}")
            self.send_error(500, f"Failed to get evaluation statistics: {str(e)}")


def start_api_server(port=8002):
    """启动API服务器"""
    try:
        server = HTTPServer(('localhost', port), APIRequestHandler)
        print(f"API服务器启动在端口 {port}")
        print(f"API地址: http://localhost:{port}")
        print("可用端点:")
        print("  GET  /api/health - 健康检查")
        print("  GET  /api/salary-analysis?days=7 - 薪资分析")
        print("  GET  /api/candidate-messages?candidate_id=1 - 候选人消息")
        print("  GET  /api/evaluate-message?message=测试消息 - 评估消息")
        print("  POST /api/evaluate-message - 评估消息(POST)")
        print("  POST /api/batch-evaluate - 批量评估消息")
        print("按 Ctrl+C 停止服务器")
        
        server.serve_forever()
        
    except KeyboardInterrupt:
        print("\nAPI服务器已停止")
    except Exception as e:
        print(f"API服务器启动失败: {e}")


if __name__ == '__main__':
    import argparse
    
    parser = argparse.ArgumentParser(description='启动API服务器')
    parser.add_argument('--port', type=int, default=8002, help='服务器端口 (默认: 8002)')
    
    args = parser.parse_args()
    start_api_server(args.port)
